package com.ydd.mqserver.mq.consumer;

import com.rabbitmq.client.Channel;
import com.ydd.common.utils.RedisUtil;
import com.ydd.mqserver.base.QueueNames;
import com.ydd.mqserver.vo.NotifyMsgSendVO;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class Consumer {

@Autowired
private RedisUtil redisUtil;

//    @RabbitListener(queues = {QueueNames.NOTIFY_MSG_QUEUE})
//    public void consumerMsg(NotifyMsgSendVO vo) {
//
//        try {
//
//            log.info("消费者收到消息");
//
//        }catch (Exception e){
//            log.error(e.getMessage());
//        }
//
//
//    }

    @RabbitListener(queues = {QueueNames.NOTIFY_MSG_QUEUE}, ackMode = "MANUAL")
    public void handleMessage(NotifyMsgSendVO vo,Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {

            String messageId = vo.getPriKey();
            System.out.println("消息ID："+messageId);
            //防止消息不被重复消费

           // redis检查消息是否已经处理过
            if (redisUtil.hasKey(messageId)) {
                System.out.println("消息已处理: " + messageId);
                channel.basicAck(deliveryTag, false);
                return;
            }

            // 处理消息
            System.out.println("处理消息: " + vo);


            redisUtil.set(messageId, "processed", 1L, TimeUnit.DAYS);

            // 手动确认签收
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {

            e.printStackTrace();
            // 拒绝签收，消息重新入队
            channel.basicReject(deliveryTag, true);
        }
    }
}
